package com.ruoyi.shop.controller.common;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.shop.domain.ShopProductImage;
import com.ruoyi.shop.service.IShopProductImageService;
import com.ruoyi.shop.util.ImageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 删除已上传的图片
 * @Author Alan Zhang
 * @Date 2020/9/27 15:31
 */
@Controller
@RequestMapping("/system/del")
public class DeleteUploadImageController {
    protected final Logger logger = LoggerFactory.getLogger(DeleteUploadImageController.class);
    @Autowired
    private IShopProductImageService shopProductImageService;


    /**
     * 删除已上传的图片文件和关联地址
     */
    @PostMapping("/img/{type}")
    @ResponseBody
    public AjaxResult img(@PathVariable("type") Integer type, Long key)
    {
        if(1 == type){
            //产品图片
            return delProductImage(key);
        } else {
            return AjaxResult.error("类型错误");
        }
    }


    /**
     * 产品图片
     * @return
     */
    private AjaxResult delProductImage(Long id){
        ShopProductImage productImage = shopProductImageService.selectShopProductImageById(id);
        if(productImage != null) {
            int rows = shopProductImageService.deleteShopProductImageById(id);
            if (rows > 0) {
                try {
                    ImageUtils.deleteFile(productImage.getImgSrc());

                    logger.info("产品图片，id：{} url:{}，{}",productImage.getId(), productImage.getImgSrc(), ShiroUtils.getLoginName());
                }catch (Exception e){
                    logger.error(e.getMessage());
                }
                return AjaxResult.success("删除成功");
            }
        }
        return AjaxResult.error("删除失败");
    }

    /**
     * 删除已上传的图片文件
     */
    @PostMapping("/imgUrl")
    @ResponseBody
    public AjaxResult imgUrl(String imgUrl)
    {
        if(ImageUtils.deleteFile(imgUrl)){
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }


}
